package co.edu.unal.franquicias.mastercard.auth;

import com.sun.jersey.api.NotFoundException;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.api.view.Viewable;
import com.sun.jersey.oauth.server.api.providers.DefaultOAuthProvider;
import com.sun.jersey.oauth.server.api.providers.DefaultOAuthProvider.Consumer;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/{user}/applications/")
public class ConsumersResource extends ResourceBase {
    // inject the DefaultOAuthProvider instance
    private @Context DefaultOAuthProvider provider;

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public Response post(Form params) {
        // make sure the right user is logged in
        checkUser();
        // only allow if the user has write access
        checkWrite();
        // register a new consumer
        Consumer consumer = provider.registerConsumer(user, params);
        // redirect to the consumer detail
        return Response.seeOther(uriInfo.getRequestUriBuilder()
                .path("{consumerKey}").build(consumer.getKey())).build();
    }

    @Path("register")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable getHtml() {
        // make sure the right user is logged in
//        checkUser();
        return new Viewable("/consumerregistration", null);
    }

    @Path("{consumerKey}")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable getConsumer(@PathParam("consumerKey") String consumerKey) {
        checkUser();
        // retrieve the consumer, check the owner and pass it to the viewable
        DefaultOAuthProvider.Consumer c = provider.getConsumer(consumerKey);
        if (!user.equals(c.getOwner())) throw new NotFoundException();
        return new Viewable("/consumer", c);
    }
}
